<?php

namespace app\admin\controller;
use think\facade\View;
use think\facade\Db;
use app\admin\logic\GoodsLogic;
use app\admin\model\Goods;

class DesignPage extends Base{

    //列表
    public function index(){

        $page = input('param.page');
        $limit = input('param.limit');
        if(input('param.field') && input('param.order')){
            $order = input('param.field').' '.input('param.order');
        }else{
            $order = Db::raw('if(is_home=0,999,is_home),id');
        }
        $type =  input('param.type',0);//0 常规设计页面 1模板库
        $into =  input('param.into')?input('into/d'):0;
        $where = array();

        if($type==1){
            //模板库
            $where[] = ['type','=',1];
        }else{
            $where[] = ['type','=',0];
        }

        if(input('param.name')) $where[] = ['name','like','%'.input('param.name').'%'];
        if(input('?param.is_home')) $where[] = ['is_home','=',input('param.is_home')];
        if(request()->isAjax()){
            $count = 0 + Db::name('designerpage')->where($where)->count();
            $data = Db::name('designerpage')->where($where)->page($page,$limit)->order($order)->select();
            return json(['code'=>0,'msg'=>'查询成功','count'=>$count,'data'=>$data]);
        }
        $count = 0 + Db::name('designerpage')->where($where)->count();
        $datalist = Db::name('designerpage')->where($where)->limit(10)->order($order)->select();
        View::assign('count',$count);
        View::assign('datalist',$datalist);
        $auth['setHome'] = true;
        $auth['rehome'] = true;
        $auth['del'] = true;
        $auth['add']  = true;
        $auth['copy'] = true;
        $auth['edit'] = true;
        $typeparam = input('type');
        View::assign('auth',$auth);
        View::assign('type',$type);
        View::assign('into',$into);
        View::assign('typeparam',$typeparam);
        View::assign('bid',0);
        return View::fetch();
    }
    public function edit(){
        $id = input('id');
        if($id){
            $info = Db::name('designerpage')->where('id',$id)->find();
        }else{
            $info = [];
        }

        $cur_url = getCurUrl();
        $pageinfo= json_decode($info['pageinfo']) ? $info['pageinfo'] : "[{id:'M0000000000000',temp:'topbar',params:{title:'默认标题',gid:0,'bgcolor':'#f5f5f5','needlogin':'0',quanxian:{'all':true},fufei:'0',showgg:0,guanggao:'".$cur_url.'/static/imgsrc/picture-1.jpg'."',hrefurl:'',ggrenqun:{'0':true},cishu:'0'}}]";
        View::assign('pageinfo',$pageinfo);
        $pagedata= $info['content'] && json_decode($info['content']) ? $info['content'] : '[]';
        $pagedata =  logic('PageLogic')->initpagecontent($pagedata);
//        dump(json_decode($pagedata,true));exit;
        View::assign('pagedata',$pagedata);

        $domain_url = getCurUrl();
        View::assign($domain_url,'domain_url');
        View::assign('info',$info);
        $color1 = tpCache('basic.color1');
        View::assign('color1',$color1);
        $map_key = tpCache('basic.qq_map_key');
        View::assign('map_key',$map_key);

        $wallet_arr = logic('Wallet')->getName();
        unset($wallet_arr['s_money']);
        View::assign('wallet_arr',$wallet_arr);

        $leixing_arr = Db::name('goods_leixing')->where('1=1')->select();
        View::assign('leixing_arr',$leixing_arr);
        View::assign('type',input('type'));
        $platform = [
            'wx' => '微信公众号',
            'h5' => 'H5',
            'wx_app' => '微信小程序',
            'app' => 'APP',
        ];
        View::assign('platform',$platform);
        $level_list = Db::name('user_level')->where('1=1')->select();
        View::assign('level_list',$level_list);
        $auth_data = 'all';
        View::assign('auth_data',$auth_data);
        View::assign('bid',0);
        $sysset = [
            'name' => '',
            'logo' => ''
        ];
        View::assign('sysset',$sysset);
        return View::fetch();
    }

    public function save(){
        $id = input('post.id/d');
        $designerpage = [];
        if($id){
            $designerpage = Db::name('designerpage')->where('id',$id)->find();
        }
        $content = input('post.content');

        $content = htmlspecialchars_decode($content);
        $content = json_decode($content,true);
        foreach($content as $k=>$v){
            if($v['temp']=='richtext'){
                $v['content'] = urldecode($v['content']);
            }
            $content[$k] = $v;
        }
        $content = json_encode($content);
        $pageinfo = input('pageinfo');
        $pageinfo = htmlspecialchars_decode($pageinfo);

        $info = array();
        //$info['content'] = geteditorcontent($content,aid);
        $info['type'] = input('type');
        $info['content'] = $content;
        $info['pageinfo'] = $pageinfo;
        $pageinfo = json_decode($pageinfo,true);
        $info['name'] = $pageinfo[0]['params']['title'];
        if(!$designerpage){
            $info['createtime'] = time();

        }
        $info['updatetime'] = time();

        if($designerpage){
            Db::name('designerpage')->where(['id'=>$designerpage['id']])->update($info);
            $pageid = $designerpage['id'];
        }else{
            $pageid = Db::name('designerpage')->insertGetId($info);
        }
        return json(['status'=>1,'msg'=>'操作成功','url'=>(string)url('index'),'pageid'=>$pageid]);
    }

    public function api(){
        $op = input('op');
        if($op=='selectproduct'){
            $proshownum = input('proshownum');
            $map = [];
            $map['is_on_sale'] = 1;
            $map['status'] = 1;
            if(input('leixing_id')){
                $map['leixing_id'] = input('leixing_id');
            }
            if(input('bid')){
                $map['sid'] = input('bid');
            }
            $lists = Db::name('goods')->where($map)->limit($proshownum)->select();
            return json($lists);
        }
        if($op=='selectarticle'){
            $shownum = input('shownum');
            $map = [];
            $map['is_open'] = 1;
            $lists = Db::name('article')->where($map)->limit($shownum)->select();
            return json($lists);
        }
        if(input('param.op') == 'selectseckill'){//查询秒杀商品
            $proshownum = input('proshownum');
            $map = [];
            $map[] = ['status','=',1];
            if(input('bid')){
                $map[] = ['sid','=',input('bid')];
            }
            $goods_ids = Db::name('seckill_product')
                ->where('status',1)
                ->where('stime','<=',time())->where('etime','>=',time())->column('goods_id');
            $map = [];
            $map[] = ['is_on_sale','=',1];
            $map[] = ['status','=',1];
            $map[] = ['goods_id','in',$goods_ids];
            if(input('leixing_id')){
                $map['leixing_id'] = input('leixing_id');
            }
            if(input('bid')){
                $map['sid'] = input('bid');
            }
            $lists = Db::name('goods')->where($map)->limit($proshownum)->select();
            logic('GoodsLogic')->getPriceNew($lists,0);
            return json($lists);
        }
    }

    //预览
    public function preview(){
        $id = input('param.id/d');
        if($id){
            $where = [];
            $where['id'] = $id;
            $info = Db::name('designerpage')->where($where)->find();
        }
        $pagedata= $info['content'] && json_decode($info['content']) ? $info['content'] : '[]';
        $pagedata =  logic('PageLogic')->initpagecontent($pagedata);
        $pageinfo= $info['pageinfo'] && json_decode($info['pageinfo']) ? $info['pageinfo'] : "[{id:'M0000000000000',temp:'topbar',params:{title:'',desc:'',img:'',kw:'',footer:'1',footermenu:'', floatico:'0',floatstyle:'right',floatwidth:'30px',floattop:'100px',floatimg:'',floatlink:''}}]";



        View::assign('info',$info);
        View::assign('pagedata',$pagedata);
        View::assign('pageinfo',$pageinfo);
        $wallet_arr = logic('Wallet')->getName();
        View::assign('wallet_arr',$wallet_arr);
        $map_key = tpCache('basic.qq_map_key');
        View::assign('map_key',$map_key);
        return View::fetch();
    }

    public function del(){
        $id = input('id');
        Db::name('designerpage')->where('id',$id)->delete();
        return json(['status'=>1,'msg'=>'删除成功']);
    }

    //复制
    public function copy(){
        $id = input('post.id/d');
        if(empty($id)) {
            return json(['status'=>0,'msg'=>'参数错误']);
        }

        $type = input('post.type/d');
        $where = [];
        $where['id'] = $id;
        $copydata = Db::name('designerpage')->where($where)->find();
        $copydata['id'] = '';
        $copydata['aid'] = aid;
        $copydata['bid'] = bid;
        $copydata['ishome'] = 0;

        //处理tab
        $content = json_decode($copydata['content'],true);
        if($content){
            foreach($content as &$cv){
                if($cv['temp'] == 'tab'){
                    $oldid = $cv['id'];
                    //生成新id
                    $cv['id'] = 'M'.date("YmdHis").rand(11111,99999);
                    //查询tab
                    $tab = Db::name('designerpage_tab')->where('tabid',$oldid)->where('aid',aid)->select();
                    if($tab){

                        //更改tab中tabid为新id
                        foreach($tab as $tv){
                            unset($tv['id']);
                            unset($tv['createtime']);
                            unset($tv['updatetime']);

                            $tabdata = [];
                            $tabdata = $tv;
                            $tabdata['tabid']      = $cv['id'];
                            $tabdata['createtime'] = time();
                            //插入数据
                            $insert = Db::name('designerpage_tab')->insert($tabdata);
                        }
                    }
                }
            }
            unset($cv);
            //重新赋值
            $copydata['content'] = json_encode($content);
        }

        $copydata['createtime'] = time();
        $copydata['updatetime'] = time();
        $id = Db::name('designerpage')->insertGetId($copydata);
        return json(['status'=>1,'msg'=>'操作成功']);
    }
    //设置成主页
    public function sethome(){
        $id = input('id/d');
        $ishome = input('is_home/d');
        if(empty($id)) {
            return json(['status'=>0,'msg'=>'参数错误']);
        }

        Db::name('designerpage')->where(['is_home'=>$ishome])->update(['is_home'=>0]);
        Db::name('designerpage')->where('id',$id)->update(['is_home'=>$ishome]);
        return json(['status'=>1,'msg'=>'操作成功']);
    }
    //取消首页
    public function rehome(){
        $id = input('post.id/d');
        if(empty($id)) {
            return json(['status'=>0,'msg'=>'参数错误']);
        }
        Db::name('designerpage')->where('id',$id)->update(['is_home'=>0]);
        return json(['status'=>1,'msg'=>'操作成功']);
    }

    //选择链接
    public function chooseurl(){
        //商品分类
        $clist = Db::name('goods_category')->field('id,name')->where('parent_id',0)->order('id')->select()->toArray();
        foreach($clist as $k=>$v){
            $child = Db::name('goods_category')->field('id,name')->where('parent_id',$v['id'])->order('id')->select()->toArray();
            foreach($child as $k2=>$v2){
                $child2 = Db::name('goods_category')->field('id,name')->where('parent_id',$v2['id'])->order('id')->select()->toArray();
                $child[$k2]['child'] = $child2;
            }
            $clist[$k]['child'] = $child;
        }
        $clist2 = [];

        //商品分组
        $glist = [];
        //文章分类
        $aclist = Db::name('article_cat')->where('parent_id',0)->order('sort_order desc,cat_id')->select()->toArray();
        foreach($aclist as $k=>$v){
            $aclist[$k]['child'] = Db::name('article_cat')->where('parent_id',$v['cat_id'])->order('sort_order desc,cat_id')->select()->toArray();
        }
        $bclist = [];
        View::assign('bclist',$bclist);
        View::assign('clist',$clist);
        View::assign('clist2',$clist2);
        View::assign('glist',$glist);
        View::assign('aclist',$aclist);

        $rwvideoad = ['id'=>'','givescore'=>'','givemoney'=>'0','givemoneyparent'=>'0','givetimes'=>'1','givetimestotal'=>'999'];
        $oldhrefurl = urldecode(input('param.oldhrefurl'));
        if($oldhrefurl && strpos($oldhrefurl,'rewardedVideoAd::') === 0){
            $rwvideoadId = substr($oldhrefurl,17);
            $rwvideoad = Db::name('designerpage_rwvideoad')->where('id',$rwvideoadId)->find();
        }
        if($oldhrefurl && strpos($oldhrefurl,'miniProgram::') === 0){
            $rwvideoadId = explode('|',$oldhrefurl)[3];
            $rwvideoad = Db::name('designerpage_rwvideoad')->where('id',$rwvideoadId)->find();
        }
        View::assign('rwvideoad',$rwvideoad);
        //var_dump($oldhrefurl);

        $type = input('type');
        View::assign('type',$type);
        $callback = input('callback')?:'';
        View::assign('callback',$callback);

        $leixing_arr = Db::name('goods_leixing')->where('1=1')->select()->toArray();
        View::assign('leixing_arr',$leixing_arr);
        $platform = config('extra_platform');
        View::assign('platform',$platform);
        return View::fetch();
    }
    //选择坐标
    public function choosezuobiao(){
        $map_key_qq = tpCache('basic.qq_map_key');
        View::assign('map_key_qq',$map_key_qq);
        return View::fetch();
    }

    //地图搜索
    public function searchFormMap(){
        $keyword = input('post.keywords');
        $lat = input('post.lat');
        $lng = input('post.lng');

        if(empty($keyword) || empty($lat) || empty($lng)){
            return json(['status' => 0, 'msg' => '参数错误']);
        }
        $mapqq = new \app\common\logic\MapQQ();
        $results = $mapqq->searchNearbyPlace($keyword,['type'=>'city','lat'=>$lat,'lng'=>$lng],'',1);
        if($results['status'] == 1){
            if(empty($results['data']) && isset($results['cluster'])){
                return json(['status' => 0, 'msg' => '请输入详细地址']);
            }
            return json(['status' => 1, 'data' => $results['data']]);
        }
        return json(['status' => 0, 'msg' => '请求失败']);
    }
}